package com.rrd.hive.udf.brickhouse.udf.date;



import org.apache.hadoop.hive.ql.exec.UDF;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.PeriodFormatter;

/**
 * UDF that receives date, date format (such as "YYYY-MM-dd HH:mm:ss") and
 * period in ISO8601, it adds period in seconds to date.
 *
 * Example: add_iso_period(date, 'YYYY-MM-dd HH:mm:ss', 'PT02H00M')
 */
public class AddISOPeriodUDF extends UDF {

	private static final PeriodFormatter periodFormatter = org.joda.time.format.ISOPeriodFormat
			.standard();

	public String evaluate(String dateString, String dateFormat, String periodString) {
		if (dateString == null) {
			return null;
		}

		if (dateFormat == null) {
			dateFormat = "YYYY-MM-dd HH:mm:ss";
		}

		DateTimeFormatter dateFormatter = org.joda.time.format.DateTimeFormat.forPattern(dateFormat);
		DateTime input = dateFormatter.parseDateTime(dateString);

		Duration duration = periodFormatter.parsePeriod(periodString).toStandardDuration();
		long seconds = duration.getStandardSeconds();

		DateTime output = input.plusSeconds(Long.valueOf(seconds).intValue());
		return dateFormatter.print(output);
	}
}
